package com.bestv.search.common.dao.hibernate;

import com.bestv.search.common.dao.TopNCacheDao;
import com.bestv.search.common.model.TopNCache;
import org.hibernate.Query;
import org.hibernate.Session;

import java.util.List;

public class TopNCacheDaoHibernate extends GenericDaoHibernate<TopNCache, Long> implements TopNCacheDao {

    public TopNCacheDaoHibernate() {
        super(TopNCache.class);
    }

    @SuppressWarnings("unchecked")
    public List<TopNCache> get(String type, String subType, String category, int topN) {
        String hql = null;
        String values[] = null;
        if (category == null) {
            hql = "from TopNCache where type = ? and subType = ? order by rankNo asc ";
            values = new String[]{type, subType};
        } else {
            hql = "from TopNCache where type = ? and subType = ? and customCategory = ? order by rankNo asc";
            values = new String[]{type, subType, category};
        }

        List<TopNCache> list = super.getHibernateTemplate().find(hql, values);

        return list == null ? null : list.subList(0, Math.min(list.size(), topN));
    }

    @SuppressWarnings("unchecked")
    public List<TopNCache> getIncrease(String type, String subType, String category, int topN) {
        String hql = null;
        String values[] = null;
        if (category == null) {
            hql = "from TopNCache where type = ? and subType = ? order by increaseNo desc ";
            values = new String[]{type, subType};
        } else {
            hql = "from TopNCache where type = ? and subType = ? and customCategory = ? order by increaseNo desc ";
            values = new String[]{type, subType, category};
        }
        List<TopNCache> list = super.getHibernateTemplate().find(hql, values);

        return list == null ? null : list.subList(0, Math.min(list.size(), topN));
    }

    public void updateMediaCodeHitCache(String type) {
        String sql = "call updateMediaCodeHitCache(?)";
        Session session = null;
        try {
            session = getSession();
            Query query = session.createSQLQuery(sql);
            query.setString(0, type);
            query.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
    }

    public int deleteHistroyByKeyword(String keyword) {
        String hql = "delete from TopNCache where name = ? and subType='keyword'";
        Session session = null;
        try {
            session = getSession();
            Query query = session.createQuery(hql);
            query.setString(0, keyword);
            return query.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }

        return 0;
    }
}
